package com.example.gridlayoutdemo08;

import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;
import android.view.DragEvent;
import android.view.View;
import android.widget.GridLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gridlayoutdemo08.view.DragDialog;
import com.example.gridlayoutdemo08.view.DragGridLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private GridLayout mGridLayout;
    private int index;
    private View dragedView;

    private View.OnLongClickListener olcl = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            /*第一个参数与第三个参数用来传递数据和状态,给null
            第二个参数用来创建拖拽阴影
            第四个参数,未定义给0*/
            dragedView = v;
           // v.setEnabled(false);//变红虚线
            v.startDrag(null,new View.DragShadowBuilder(v),null,0);
            return true;
        }
    };

    /**
     * DragEvent.ACTION_DRAG_STARTED  : 开始拖拽时执行一次
     * DragEvent.ACTION_DRAG_ENDED      ：结束拖拽后，执行一次
     * DragEvent.ACTION_DRAG_ENTERED    ：当拖拽阴影进入设置了拖拽监听的控件范围内的一瞬间调用一次这个方法
     * DragEvent.ACTION_DRAG_EXITED     ：当拖拽阴影离开设置了拖拽监听的控件范围内的一瞬间调用一次这个方法
     * ACTION_DRAG_LOCATION             ：当拖拽阴影在设置了拖拽监听的控件范围内进行移动时，实时调用
     * DragEvent.ACTION_DROP            ：在设置了拖拽监听的控件范围内，手指松开，drop会被调用一次
     */
    private View.OnDragListener odl = new View.OnDragListener() {
        //当前接收拖拽事件的视图对象:gridlayout
        @Override
        public boolean onDrag(View v, DragEvent event) {
            Toast.makeText(MainActivity.this,getDragEventAction(event),Toast.LENGTH_SHORT).show();
            System.out.println("DragEvent:"+getDragEventAction(event));
            switch (event.getAction()){
                case DragEvent.ACTION_DRAG_STARTED:
                //在开始拖拽的时候,定义出每个子控件的矩形数组
                initRects();
                break;
                case DragEvent.ACTION_DRAG_LOCATION:
                //实时判断手指是否进入了子控件范围内
                    int touchIndex = getTouchIndex(event);
                    if (touchIndex>-1 && dragedView !=null && dragedView != mGridLayout.getChildAt(touchIndex)){
                        mGridLayout.removeView(dragedView);
                        mGridLayout.addView(dragedView,touchIndex);
                    }
                 break;
            }
            return true;
        }
    };
    private DragGridLayout mGrid1;
    private DragGridLayout mGrid2;

    //实时判断手指是否进入了子控件范围内
    private int getTouchIndex(DragEvent event) {
        for (int i =0; i<mRects.length;i++){
            if (mRects[i].contains(((int)event.getX()),((int)event.getY()))){
                return i;
            }
        }
         return -1;
    }

    private Rect[] mRects;

    //定义出每个子控件的矩形数组
    private void initRects() {
        mRects = new Rect[mGridLayout.getChildCount()];
        for (int i = 0;i<mGridLayout.getChildCount();i++){
            View childView = mGridLayout.getChildAt(i);
            mRects[i] = new Rect(childView.getLeft(),childView.getTop(),childView.getRight(),
                    childView.getBottom());
        }
    }

    //SparseArray<String> 相当于hashmap,但更高效，谷歌官方推荐
    static SparseArray<String> dragEventType = new SparseArray<String>();

    static {
        dragEventType.put(DragEvent.ACTION_DRAG_STARTED, "STARTED");
        dragEventType.put(DragEvent.ACTION_DRAG_ENDED, "ENDED");
        dragEventType.put(DragEvent.ACTION_DRAG_ENTERED, "ENTERED");
        dragEventType.put(DragEvent.ACTION_DRAG_EXITED, "EXITED");
        dragEventType.put(DragEvent.ACTION_DRAG_LOCATION, "LOCATION");
        dragEventType.put(DragEvent.ACTION_DROP, "DROP");
    }

    public static String getDragEventAction(DragEvent de) {
        return dragEventType.get(de.getAction());
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGridLayout = (GridLayout) findViewById(R.id.gridlayout);
        mGridLayout.setOnDragListener(odl);

        mGrid1 = (DragGridLayout) findViewById(R.id.grid1);
        List<String> items1 = new ArrayList<>();
        items1.add("上海");
        items1.add("昆山");
        items1.add("苏州");
        items1.add("无锡");
        items1.add("常州");
        items1.add("丹阳");
        items1.add("镇江");
        items1.add("南京");
        items1.add("马鞍山");
        mGrid1.setAllowDrag(true);
        mGrid1.setItems(items1);
        mGrid1.setOnClickItemListener(new DragGridLayout.OnClickItemListener() {
            @Override
            public void onClickItem(TextView tv) {
                //将返回的文本删除,添加到grid2里边
                mGrid1.removeView(tv);
                String text = tv.getText().toString();
                mGrid2.addItem(text);
            }
        });

        mGrid2 = (DragGridLayout) findViewById(R.id.grid2);
        List<String> items2 = new ArrayList<>();
        items2.add("北京");
        items2.add("武汉");
        items2.add("长沙");
        items2.add("杭州");
        items2.add("南昌");
        items2.add("东莞");
        items2.add("深圳");
        items2.add("广州");
        items2.add("台北");
        mGrid2.setAllowDrag(false);
        mGrid2.setItems(items2);
        mGrid2.setOnClickItemListener(new DragGridLayout.OnClickItemListener() {
            @Override
            public void onClickItem(TextView tv) {
                //将返回的文本删除,添加到grid1里边
                mGrid2.removeView(tv);
                String text = tv.getText().toString();
                mGrid1.addItem(text);
            }
        });
    }
    public void addItem(View view){
        final DragDialog dialog = new DragDialog(MainActivity.this);
        List<String> items1 = new ArrayList<>();
        items1.add("上海");
        items1.add("昆山");
        items1.add("苏州");
        items1.add("无锡");
        items1.add("常州");
        items1.add("丹阳");
        items1.add("镇江");
        items1.add("马鞍山");
        items1.add("南京");

        List<String> items2 = new ArrayList<>();
        items2.add("北京");
        items2.add("武汉");
        items2.add("长沙");
        items2.add("杭州");
        items2.add("南昌");
        items2.add("东莞");
        items2.add("深圳");
        items2.add("广州");
        items2.add("台北");
        dialog.setShowAndHideItems(items1, items2);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface d) {
                Toast.makeText(MainActivity.this, dialog.getShowItems().toString(), Toast.LENGTH_SHORT).show();
            }
        });
        dialog.show();

       /* Dialog dialog = new Dialog(MainActivity.this,R.style.dialog_style);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.height = GridLayout.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.TOP;
        dialog.setContentView(R.layout.dialog);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();*/
        /*//给gridlayout添加子控件
        TextView tv = new TextView(MainActivity.this);
        int margin = 5;
        GridLayout.LayoutParams params = new GridLayout.LayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels/
                mGridLayout.getColumnCount()-2*margin;
        params.height = GridLayout.LayoutParams.WRAP_CONTENT;
        tv.setGravity(Gravity.CENTER);//设置文字居中
        //params.setGravity(Gravity.CENTER);
        params.setMargins(margin,margin,margin,margin);
        tv.setLayoutParams(params);
        tv.setBackgroundResource(R.drawable.tv_bg);
        tv.setText(index+"");
        index++;

        tv.setOnLongClickListener(olcl);
      //  mGridLayout.addView(tv);
        mGridLayout.addView(tv,0);*/
    }
}
